import React, { useEffect, useRef, useState, useContext } from 'react';
import useMousePositions from '../hooks/useMousePositions'
import { ThemeContext } from '../App'

const LikeButton: React.FC = () => {
  // 复用Hook的逻辑
  const position = useMousePositions();
  const [like, setLike] = useState(0);
  const [on, setOn] = useState(true);
  // Ref在所有render中保持着唯一的引用，在不同的render中没有隔离
  const likeRef = useRef(0);
  const didMountRef = useRef(false);
  const domRef = useRef<HTMLInputElement>(null);
  // useContext
  const theme = useContext(ThemeContext);
  console.log(theme);
  // 设置样式
  const style = {
    background: theme.background,
    color: theme.color
  }
  useEffect(() => {
    document.title = `点击了${like}次`;
    // [like]表示只有like被修改的时候才执行useEffect（第一次渲染也会执行
    console.log('effect 被执行了');
  }, [like]);
  useEffect(() => {
    if (didMountRef.current) {
      console.log('this is updated');
    } else {
      didMountRef.current = true
    }
  })
  useEffect(() => {
    if (domRef && domRef.current) {
      domRef.current.focus()
    }
  })

  function handleAlertClick() {
    setTimeout(() => {
      alert(`点击了${likeRef.current}次`)
    }, 3000)
  }
  return (
    <div>
      <input ref={domRef} type="text" />
      <button style={style} onClick={() => {setLike(like + 1); likeRef.current++}}>
        👍{like}
      </button>
      <button onClick={() => {handleAlertClick();}}>alert</button>
      <p>
        X: {position.x}, Y: {position.y}
      </p>
      <button onClick={() => {setOn(!on)}}>
        {on ? 'ON' : 'OFF'}
      </button>
    </div>
  );
}

export default LikeButton;